//
//  AreaSelectViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-8-22.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "AreaSelectViewController.h"
#import "Config.h"
#import "Helper.h"

//  -业务逻辑细节说明-
//
//  @abstract       此类中的逻辑主要体现在向HTML中提交要显示的城市数据，以及从HTML中获取显示中的城市数据。具体相见私有方法中的方法注释

//  @discussion     1、webview加载完成后，先会显示出所有的区域，然后根据上级VC是否传入了要默认勾选的或显示的区域信息进行二次渲染（即是否在用户修改的时候，要显示出用户以前选择过的）。
//                  2、用户选择过区域或者省市后，会同时体现在当前webview上。
//

//  @notes          1、需要将选择后的最终数据传递给上级页面或者需要对比修改前后的数据时，始终都通过JS获取HTML显示的城市数据，这样可以简化数据操作。
//                  2、“海外”特殊一点，把它当做一个特殊的二级城市看待。


//  -类修改日志-
//  修改人   修改时间   针对版本   修改描述

@interface AreaSelectViewController ()

@end

@implementation AreaSelectViewController
@synthesize areaFreightRegionArray = _areaFreightRegionArray;
@synthesize delegate = _delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _areaArray = @[@"华东",@"华北",@"华中",@"华南",@"东北",@"西北",@"西南",@"港澳台",@"海外"];
        _areasSelected = [NSMutableArray new];
        _currentArea = [NSMutableArray new];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.title = _L(@"vc_title_078");
    
    //返回按钮
    UIButton *backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    [backButton addTarget:self action:@selector(backButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    //保存
    UIButton *saveButton = [Helper buttonWithStyle:ButtonStyleNavigationSave];
    [saveButton addTarget:self action:@selector(saveButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:saveButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    NSString* filePath = [[NSBundle mainBundle] pathForResource:@"select_area" ofType:@"html"];
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH, _SYS_FRAME_HEIGHT-44.0f)];
    _webView.delegate = self;
    //    _webView.scrollView.bounces = NO;
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
    [self.view addSubview:_webView];
    
    _areaDic = [NSDictionary dictionaryWithObjects:@[@"area_east",@"area_north",@"area_center",@"area_south",@"area_northeast",@"area_northwest",@"area_southwest",@"area_gwt",@"area_foreign"]
                                           forKeys:@[@"华东",@"华北",@"华中",@"华南",@"东北",@"西北",@"西南",@"港澳台",@"海外"]];
    
    //解析城市数据字符串
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)[0];
    NSString *filename = [path stringByAppendingPathComponent:@"location_standard.plist"];
    
    _provinces = [NSArray arrayWithContentsOfFile:filename];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 私有方法

//根据HTML的返回情况，组装服务器所需要的数据
//HTML返回的结果有三种情况：
//1、@“all”,表示此区域下所有的一级省市都被勾选
//2、@"",表示此区域下的一级省市都没有被勾选
//3、最后一种情况，表示区域下的一级省市部分被选中
- (NSMutableArray *)areaInfoSelected:(NSString *)area
{
    NSMutableArray *areaInfoSelected = [NSMutableArray new];
    
    NSString *result = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"select_result('%@')",area]];
    
    //如果区域是全选，就要组装全部的省市及其二级城市
    if ([result isEqualToString:@"all"]) {
        
        //单独处理海外
        if ([@"海外" isEqualToString:area]) {

            [areaInfoSelected addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                        area, @"province",
                                        @"海外", @"city",
                                        [NSNumber numberWithInteger:1], @"cityNum",
                                         area, @"anArea", nil]];
            return areaInfoSelected;
        }
        
        //找到一个区域下所有的省市集合
        NSMutableArray *provincesInfoInArea = [NSMutableArray new];
        for (NSDictionary *province in _provinces) {
            
            if ([area isEqualToString:province[@"area"]]) {
                [provincesInfoInArea addObject:province];
            }
        }
        
        for (NSDictionary *provinceDic in provincesInfoInArea) {
            
            NSMutableArray *cities = [NSMutableArray new];
            
            for (NSDictionary *city in provinceDic[@"cities"]) {
                
                [cities addObject:city[@"name"]];
            }
            
            [areaInfoSelected addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                        provinceDic[@"name"], @"province",
                                        [cities componentsJoinedByString:@","], @"city",
                                        [NSNumber numberWithInteger:[cities count]], @"cityNum",
                                         area, @"anArea", nil]];
        }
    }
    else if ([result isEqualToString:@""]) {
        
        
    }
    
    //HTML返回的是以“，”隔开的二级城市的字符串
    else {

        for (NSDictionary *dic in _areasSelected) {
            
            if ([area isEqualToString:dic[@"anArea"]]) {
                
                [areaInfoSelected addObject:dic];
            }
        }
        
        return areaInfoSelected;
        
        
    }
    
    return areaInfoSelected;
}

//显示已选中的省市
//此方法是上一个方法（areaInfoSelected）的逆，如果提交@“all”给HTML，表示对应区域下所有的一级省市都被勾选；
//如果提交@“”，表示不勾选；
//如果提交一个指定格式的JSON，就显示区域下部分一级省市。json格式看看源代码
- (void) showAreaInfo:(NSMutableArray *)areaInfo
{
    //将数据按区域分组处理,一个区域下对应一个省市列表
    for (int i=0; i<[[_areaDic allKeys] count]; i++) {
        
        //找到一个区域下所有要显示的省市集合
        NSMutableArray *provincesInfo = [NSMutableArray new];
        
        NSMutableArray *provincesName = [NSMutableArray new];
        NSMutableArray *cityNum = [NSMutableArray new];
        
        NSInteger provincesNumShowing = 0;
        for (int j=0; j<areaInfo.count; j++) {
            
            if ([areaInfo[j][@"anArea"] isEqualToString:[_areaDic allKeys][i]]) {
                
                [provincesInfo addObject:areaInfo[j]];
                provincesNumShowing += [areaInfo[j][@"cityNum"] integerValue];
            }
        }
        
        //得到一个区域下实际的二级城市的个数
        NSInteger provincesNum = 0;
        for (NSDictionary *province in _provinces) {
            
            if ([[_areaDic allKeys][i] isEqualToString:province[@"area"]]) {
                
                if ([[_areaDic allKeys][i] isEqualToString:@"海外"] && [province[@"area"] isEqualToString:@"海外"])
                {
                    provincesNum += 1;
                }
                else {
                    provincesNum += [((NSArray *)province[@"cities"]) count];
                }
            }
        }
        
        NSDictionary *areaInfo;
        
        //如果一个区域下实际的省市的二级城市个数等于所有要显示的省市集合所有二级城市的个数，那么就要传“all”，让HTML显示“整个区域”
        if (provincesNum != 0 && provincesNumShowing != 0 && provincesNum == provincesNumShowing) {
            
            areaInfo = [NSDictionary dictionaryWithObjectsAndKeys:[_areaDic allKeys][i], @"area", @"all", @"info", nil];
        }
        
        //否则，要显示出每一个省市以及每个省市的所选中的城市个数
        else if (provincesNum != 0 && provincesNumShowing != 0 && provincesNum != provincesNumShowing){
            
            for (int i=0; i<provincesInfo.count; i++) {
                
                [provincesName addObject:provincesInfo[i][@"province"]];
                [cityNum addObject:provincesInfo[i][@"cityNum"]];
                
            }

            areaInfo = [NSDictionary dictionaryWithObjectsAndKeys:[_areaDic allKeys][i], @"area", [NSDictionary dictionaryWithObjectsAndKeys:[provincesName componentsJoinedByString:@","],@"province", [cityNum componentsJoinedByString:@","], @"cityNum", nil], @"info", nil];
        }
        
        //没有要显示的
        else if (provincesNum == 0 && provincesNumShowing == 0) {
            
            areaInfo = [NSDictionary dictionaryWithObjectsAndKeys:[_areaDic allKeys][i], @"area", @"", @"info", nil];
        }
        
        else {
            
        }
        
        NSString *json;
        if ([NSJSONSerialization isValidJSONObject:areaInfo])
        {
            NSError *error;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:areaInfo options:NSJSONWritingPrettyPrinted error:&error];
            json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSLog(@"json data:%@",json);
        }
        //调用JS
        if (json != nil) {
            
            [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"show(%@);",json]];
        }
    }
}

//
////此方法返回的数组要传递给下一级选择省市的页面，表示要勾选那些省市以及要显示哪些省市对应的二级城市
////anArea ：需要处理的区域
//- (NSMutableArray *)provincesShouldPassWith:(NSString *)anArea
//{
//    NSMutableArray *provinces = [NSMutableArray new];
//    
//    if ([[_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"check_status('%@')",_areaDic[anArea]]] isEqualToString:@"true"]) {
//
//        //如果已被全选，就组装成指定格式。
//        for (NSDictionary *province in _provinces) {
//            
//            NSMutableDictionary *provinceSelectInArea;
//            if ([anArea isEqualToString:province[@"area"]]) {
//
//                NSMutableArray *cities = [NSMutableArray new];
//                
//                for (NSDictionary *city in province[@"cities"]) {
//                    
//                    [cities addObject:city[@"name"]];
//                }
//                
//                provinceSelectInArea = [NSMutableDictionary dictionaryWithObjectsAndKeys:
//                                    province[@"name"], @"province",
//                                    [cities componentsJoinedByString:@","], @"city",
//                                    [NSNumber numberWithInteger:[cities count]], @"cityNum",
//                                    anArea, @"anArea", nil];
//                
//                
//                [provinces addObject:provinceSelectInArea];
//                
//            }
//            
//            
//        }
//    }
//    else {
//        
//        //如果是修改区域时，意思就是前面已经传过来了需要显示的区域。（JSON格式参照API）
//        if (_areasSelected != nil) {
//            
//            //找到某一个区域所要显示的省市数据
//            for (int i=0; i<_areasSelected.count; i++) {
//                
//                if ([_areasSelected[i][@"anArea"] isEqualToString:anArea]) {
//                    
//                    [provinces addObject:_areasSelected[i]];
//                }
//            }
//        }
//    }
//    
//    return provinces;
//}
//
////当区域整个被勾选时
//- (NSMutableArray *)areaArrayForAll:(NSString *)anArea
//{
//    
//    NSMutableArray *provincesSelected = [NSMutableArray new];
//    
//    NSMutableArray *provincesInArea = [NSMutableArray new];
//    
//    //得到一个区域下，所应该显示的一级省市
//    for (NSDictionary *province in _provinces) {
//        
//        if ([anArea isEqualToString:province[@"area"]]) {
//            [provincesInArea addObject:province];
//        }
//    }
//    
//    //遍历每一个一级城市，组装各个数据
//    for (int i=0; i<provincesInArea.count; i++) {
//        
//        NSMutableArray *cities = [NSMutableArray new];
//        
//        if ([@"海外" isEqualToString:provincesInArea[i][@"name"]]) {
//            [cities addObject:@"海外"];
//        }
//        else {
//            for (NSDictionary *city in provincesInArea[i][@"cities"]) {
//                
//                [cities addObject:city[@"name"]];
//            }
//        }
//        
//        [provincesSelected addObject:[NSDictionary dictionaryWithObjectsAndKeys:
//                                      provincesInArea[i][@"name"], @"province",
//                                      [cities componentsJoinedByString:@","], @"city",
//                                      [NSNumber numberWithInteger:[cities count]], @"cityNum",
//                                      anArea, @"anArea", nil]];
//        
//    }
//    
//    return provincesSelected;
//    //    NSLog(@"%@", provincesSelected);
//    
////    return [NSDictionary dictionaryWithObjectsAndKeys:provincesSelected, @"provinces", anArea, @"area", nil];
//}

//从HTML页面中获取一次每个区域下被选中的省市信息
- (void)currentAreaArray
{
    if (_currentArea.count != 0) {
        [_currentArea removeAllObjects];
    }
    
    //找出一个区域下要显示的省市及其二级城市的信息，组成列表
    for (int i=0; i<_areaArray.count; i++) {
        
        NSMutableArray *province = [self areaInfoSelected:_areaArray[i]];
        
        if (province != nil) {
            [_currentArea addObjectsFromArray:province];
        }
    }
}

#pragma mark - 事件

- (void)backButtonEvent:(id)sender
{
    [self currentAreaArray];
    
    if ([_currentArea isEqualToArray:_areaFreightRegionArray]) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    else {
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:_L(@"alert_122") delegate:self cancelButtonTitle:_L(@"btn_no_01") otherButtonTitles:_L(@"btn_yes_01"), nil];
        alertView.tag = 1;
        [alertView show];
    }
}

- (void)saveButtonEvent:(id)sender
{
    
    [self currentAreaArray];

    if ([_delegate respondsToSelector:@selector(areaSelected:)]) {
        [_delegate areaSelected:_currentArea];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIWebView Delegate

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [_areasSelected addObjectsFromArray:_areaFreightRegionArray];
    //设置默认要显示的省市数据
    if (_areaFreightRegionArray != nil) {

        [self showAreaInfo:_areaFreightRegionArray];
    }
//    NSLog(@"当前从服务器得到的城市：%@",_areasSelected);
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    NSArray *strArray = [request.URL.relativeString componentsSeparatedByString:@"?"];
    
    if (strArray.count == 2) {
        
        if ([strArray[0] isEqualToString:@"open:select_province"]) {
            
            NSMutableArray *provincesInArea = [NSMutableArray new];
            
            NSString *vcTitle = [strArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            //如果是海外就返回
            if ([vcTitle isEqualToString:@"海外"]) {
                return YES;
            }
            
            //得到一个区域下，所应该显示的一级省市
            for (NSDictionary *province in _provinces) {
                
                if ([vcTitle isEqualToString:province[@"area"]]) {
                    [provincesInArea addObject:province];
                }
            }
            
            ProvinceSelectViewController *provinceSelectVC = [[ProvinceSelectViewController alloc] initWithProvinces:provincesInArea];
            provinceSelectVC.title = vcTitle;
            provinceSelectVC.delegate = self;
            provinceSelectVC.currentProvinces = [self areaInfoSelected:vcTitle];
            
            [self.navigationController pushViewController:provinceSelectVC animated:YES];

        }
        
    }
    
    return true;
}

#pragma mark - ProvincesSelectedDelegate

- (void)provincesSelected:(NSMutableArray *)provinces inWhichArea:(NSString *)area
{
    NSString *area1 = area;
    //先讲勾选后的一级城市的数据显示出来
    [self showAreaInfo:provinces];
    
    //删除这个区域下的城市，再插入区域
    if (_areasSelected.count != 0) {

        for (int i=0; i<_areasSelected.count; i++) {
            
            if ([_areasSelected[i][@"anArea"] isEqualToString:area1]) {

                [_areasSelected removeObjectAtIndex:i];
                
                i--;
            }
        }
    }
    
    
    [_areasSelected addObjectsFromArray:provinces];
//    NSLog(@"二级省市选了过后：%@",_areasSelected);
}

#pragma mark - UIAlerView Delegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }    
}
@end
